<?php
require '../libs/tmhOAuth.php';
$config = include '../config.php';
$tmhOAuth = new tmhOAuth(array(
  'consumer_key'    => $config['twitter_consumer_key'],
  'consumer_secret' => $config['twitter_consumer_secret'],
));

$here = $tmhOAuth->php_self();
session_start();

// reset?
if ( isset($_REQUEST['wipe'])) {
  session_destroy();
  header("Location: {$here}");

// already got some credentials stored?
} elseif ( isset($_SESSION['access_token']) ) {
  $tmhOAuth->config['user_token']  = $_SESSION['access_token']['oauth_token'];
  $tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret'];

  $tmhOAuth->request('GET', $tmhOAuth->url('1/account/verify_credentials'));
  $array = json_decode($tmhOAuth->response['response']);
  header("Location: ".str_replace('wp-content/plugins/stSocialMediaToolbox/Toolboxes/stTwitterToolbox/login/','wp-admin/admin.php?page=stTwitterToolbox&action=setting&user_token='.$tmhOAuth->config['user_token'].'&user_secrect='.$tmhOAuth->config['user_secret'].'&username='.$array->screen_name,$here));
// we're being called back by Twitter
} elseif (isset($_REQUEST['oauth_verifier'])) {
  $tmhOAuth->config['user_token']  = $_SESSION['oauth']['oauth_token'];
  $tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];

  $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array(
    'oauth_verifier' => $_REQUEST['oauth_verifier']
  ));
  $_SESSION['access_token'] = $tmhOAuth->extract_params($tmhOAuth->response['response']);
  unset($_SESSION['oauth']);
  header("Location: {$here}");

// start the OAuth dance
} else {
  $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''), array(
    'oauth_callback' => $here
  ));

  if ($code == 200) {
    $_SESSION['oauth'] = $tmhOAuth->extract_params($tmhOAuth->response['response']);
    $method = 'authenticate';
    header("Location: " . $tmhOAuth->url("oauth/{$method}", '') .  "?oauth_token={$_SESSION['oauth']['oauth_token']}");

  } else {
    // error
    $tmhOAuth->pr(htmlentities($tmhOAuth->response['response']));
  }
}

?>
